<?php
namespace app\common\loglic;

use app\common\loglic\Model;

class User extends Model
{
    //当前用户信息
    private $currentUser = [];
    
    //COOKIE过期时间
    public $cookieExpire = 604800;
    
    //按用户名登录
    public function loginPassword($post=[])
    {
        //登录验证
        $this->validateRule = [
            'user_name'     => 'require',
            'user_pass'     => 'length:6,15',
            'captcha_image' => 'require|captcha',
        ];
        $this->validateMsg = [
            'user_name.require'     => '请填写用户名',
            'user_pass.length'      => '密码长度6-15位',
            'captcha_image.require' => '请填写验证码',
            'captcha_image.captcha' => '验证码不正确', 
        ];
        if(!$this->validateData($post)){
            return false;
        }
        //查询用户
        $user = $this->get([
            'where' => [
                ['user_name','eq',$post['user_name']]
            ],
        ]);
        if(!$user = $this->getData($user)){
            $this->error = '此用户未注册';
            return false;
        }
        //用户状态
        if(!in_array($user['user_status'],['normal','reset'])){
            $this->error = '此用户已被封禁';
            return false;
        }
        //用户密码
        if(md5(trim($post['user_pass'])) != $user['user_pass']){
            $this->error = '密码不正确';
            return false;
        }
        //设置当前用户
        $this->currentUser = $user;
        //设置登录信息码
        if(!$this->setAuthCookie($user['user_id'],$this->cookieExpire)){
            $this->error = '请开启浏览器COOKIE功能';
            return false;
        }
        //返回结果
        return $this->currentUser;
    }
    
    /**
     * 设置当前登录的用户信息,但不会登录该用户
     * @return array
     */
    public function setCurrentUser($userId=0)
    {
        //有效用户查库
        if($userId > 0){
            //是否已经有当前用户信息
            if($userId == $this->currentUser['user_id']){
                return $this->currentUser;
            }
            //数据库查询有效用户ID
            if($user = $this->getId($userId, false, false)){
                $this->currentUser = $user;
                return $this->currentUser;
            }
        }
        //设为游客
        $this->currentUser = [
            'user_id'    => 0,
            'user_name'  => 'guest',
            'user_roles' => ['guest'],
            'user_score' => 0,
            'user_caps'  => [],
        ];
        return $this->currentUser;
    }
    
    /**
     * 获取当前登录的用户信息
     * @return array
     */
    public function getCurrentUser()
    {
        return $this->setCurrentUser($this->validateAuthCookie());
    }
    
    /**
     * 返回当前登录用户ID
     * @return int 用户ID
     */
    public function getCurrentUserId()
    {
        return $this->validateAuthCookie();
    }
    
    /**
     * 设置当前用户登录的cookie后才会登录(需要先设置当前用户)
     * @param int $userId 用户ID
     * @param int $expire 过期时间(0=关闭浏览器失效)
     * @return bool
     */
    public function setAuthCookie($userId, $expire=0)
    {
        if($this->currentUser['user_id'] < 1){
            return false;
        }
        if($userId == $this->currentUser['user_id']){
            // 服务端密钥
            $serverSecert = $this->sessionHash($this->currentUser['user_id']);
            // 客户端密钥
            $userCookie = $this->cookieHash($serverSecert);
            // 写入COOKIE
            cookie('login_client', $this->currentUser['user_id'].'%'.$userCookie, $expire);
            // 返回结果
            return true;
        }
        return false;
    }
    
    /**
     * 通过COOKIE信息验证当前用户是否登录
     * @return int 用户ID
     */
    public function validateAuthCookie()
    {
        //获取COOKIE
        list($user_id, $user_cookie) = explode('%', input('cookie.login_client'));//分割userId与Hash
        //强制整数
        $user_id = intval($user_id);
        if($user_id < 1){
            return 0;
        }
        //获取服务端密钥
        $serverSecert = input('session.login_secert/s');
        //服务端密钥已过期（Session过期）
        if(!$serverSecert){
            //数据库获取
            if(!$user = $this->getId($user_id, false, false)){
                $this->clearAuthCookie();
                return 0;
            }
            //设置当前用户
            $this->currentUser = $user;
            //重新生成服务端密钥
            $serverSecert = $this->sessionHash($user['user_id']);
            //缓存服务端密钥（Session保存）
            session('login_secert', $serverSecert);
        }
        // 验证密钥
        if($user_cookie != $this->cookieHash($serverSecert)){
            $this->setCurrentUser(0);//设置为游客
            $this->logout();//清除COOKIE,SESSION
            return 0;
        }
        // 返回已登录ID
        return $user_id;
    }
    
    /**
     * 生成加密的SESSION信息（服务端）
     * @param string $userId 用户ID
     * @return
     */
    private function sessionHash($userId=0)
    {
        return md5(config('user.secret').$userId);
    }
    
    /**
     * 生成加密的COOKIE信息(客户端)
     * @param string $userSecert 服务端密钥
     * @return
     */
    private function cookieHash($userSecert='userSession')
    {
        $hash = [];
        $hash[0] = $userSecert;
        $hash[1] = request()->header('user-agent');
        //$hash[2] = request()->ip();
        return sha1(implode('',$hash));
    }
    
    /**
     * 生成Token
     * @version 1.0.30
     * @param int $userId 用户ID
     * @return string
     */
    public function tokenCreate($userId=0)
    {
        return md5(uniqid(microtime(true).$userId.config('user.secret'),true));
    }
    
    /**
     * 生成TOKEN过期时长
     * @version 1.0.30
     * @param string $user_expire 过期时间多少天后
     * @return string $string linux时间戳
     */
    public function tokenExpire($userExpire=30)
    {
        $userExpire = xfEmpty($userExpire,30);
        return strtotime("+$userExpire days");
    }
    
    /**
    * 用户退出
    * @return mixed
    */
    public function logout()
    {
        $this->clearAuthCookie();
        $this->clearAuthSession();
    }
    
    /**
     * 清除客户端登录COOKIE
     * @return 
     */
    public function clearAuthCookie()
    {
        cookie('login_client', null);
    }
    
    /**
     * 清除服务端验证密钥SESSION
     * @return
     */
    public function clearAuthSession()
    {
        session('login_secert', null);
    }
    
    //修改器
    public function setData($action='save', $data=[])
    {
        if($action == 'save'){
            $data['user_pass']        = md5($data['user_pass']);
            $data['user_roles']       = config('user.roles');
            $data['user_caps']        = config('user.caps');
        }elseif($action == 'update'){
            $data['user_caps']        = explode(chr(13),$data['user_caps']);
            if($data['user_pass']){
                $data['user_pass']    = md5($data['user_pass']);
            }else{
                unset($data['user_pass']);
            }
        }
        //通用
        $ip = request()->ip();
        $data['user_token']       = $this->tokenCreate(0);
        $data['user_expire']      = $this->tokenExpire(config('user.expire'));
        $data['user_name']        = xfEmpty($data['user_name'],uniqid());
        $data['user_create_ip']   = xfEmpty($data['user_create_ip'],$ip);
        $data['user_update_ip']   = xfEmpty($data['user_update_ip'],$ip);
        //返回
        return ['user'=>$data];
    }
    
    //获取器
    public function getData($data=[])
    {
        if(!$data = xfResult($data)){
            return null;
        }
        return $data;
    }

    //添加一条
    public function save($data=[])
    {
        return $this->modelSave('common/User', $this->setData('create',$data));
    }

    //按条件删除
    public function delete($where=[])
    {
        return $this->modelDelete('common/User', $where);
    }
    
    //按条件修改
    public function update($where=[],$data=[])
    {
        return $this->modelUpdate('common/User', $where, $this->setData('update',$data));
    }

    //按条件查询一个用户（模型类）
    public function get($args=[])
    {
        return $this->modelGet('common/User', $args);
    }

    //按条件查询多条测评（模型类）
    public function all($args=[])
    {
        return $this->ModelSelect('common/User', $args);
    }
    
    //按条件分页查询多条测评（模型类）
    public function allPage($args=[], $pageSize=10, $pageNumber=1, $isTotal=false, $pagePath='')
    {
        return $this->modelSelectPage('common/User', $args, $pageSize, $pageNumber, $isTotal, $pagePath);
    }

    //按条件查询一条测评
    public function find($args=[])
    {
        return $this->dbGet('user', $args);
    }
    
    //按条件查询多条用户
    public function select($args=[])
    {
        return $this->dbSelect('user', $args);
    }
    
    //按条件分页查询多条用户
    public function selectPage($args=[], $pageSize=10, $pageNumber=1, $isTotal=false, $pagePath='')
    {
        return $this->dbSelectPage('user', $args, $pageSize, $pageNumber, $isTotal, $pagePath);
    }

    //按主键ID删除
    public function deleteId($userId=0)
    {
        if(!$userId){
            return 0;
        }
        return $this->delete(['user_id'=>$userId]);
    }

    //按ID查询一个用户（模型类）
    public function getId($id=0, $cache=false, $status=false)
    {
        $where = [];
        $where[] = ['user_id','eq',$id];
        if($status){
            array_push($where,['user_status','eq',$status]);
        }
        $result = $this->get([
            'where' => $where,
            'cache' => $cache,
        ]);
        return $this->getData($result);
    }

    //按主键ID修改
    public function updateId($userId=0, $data=[])
    {
        if(!$userId){
            return 0;
        }
        return $this->update(['user_id'=>$userId],$data);
    }
    
    //通过手机号查询userId
    public function getIdByMobile($userMobile='')
    {
        $this->error = '用户不存在';
        if($userMobile){
            return db('user')->where('user_mobile','eq',$userMobile)->value('user_id');
        }
        return 0;
    }

    //通过邮箱查询userId
    public function getIdByEmail($userEmail='')
    {
        $this->error = '用户不存在';
        if($userEmail){
            return db('user')->where('user_email','eq',$userEmail)->value('user_id');
        }
        return 0;
    }

    //按ID查询一条测评
    public function findId($id=0, $cache=false, $status=false)
    {
        $where = [];
        $where[] = ['user_id','eq',$id];
        if($status){
            array_push($where,['user_status','eq',$status]);
        }
        return $this->find([
            'where' => $where,
            'cache' => $cache,
        ]);
    }

    //通过手机号查询userId
    public function findIdByMobile($userMobile='')
    {
        $this->error = '用户不存在';
        if($userMobile){
            return db('user')->where('user_mobile','eq',$userMobile)->value('user_id');
        }
        return 0;
    }

    //通过用户名查询userId
    public function findIdByName($userName='')
    {
        $this->error = '用户不存在';
        if($userMobile){
            return db('user')->where('user_name','eq',$userName)->value('user_id');
        }
        return 0;
    }

    /**
     * 将urlPid写入COOKIE中(后者推广覆盖前者)
     * @version 1.0.0 首次引入
     * @return boole 无
     */
    public function pidSet()
    {
        $userPid = input('pid/d', 0);
        if($userPid < 1){
            return false;
        }
        cookie('pid', $userPid, 2592000);
        return true;
    }

    /**
     * 读取PID
     * @version 1.0.0 首次引入
     * @return number 上级ID
     */
    public function pidGet()
    {
        return intval(cookie('pid'));
    }

    /**
     * 更新字段值
     * @version 1.0.0 首次引入
     * @return bool 操作结果
     */
    public function fieldUpdate($ids=[], $field='user_status', $value='normal')
    {
        if(!$ids || !$value){
            return false;
        }
        return db('user')->where('user_id','in',$ids)->setField($field, $value);
    }
}